// pages/productList/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        tab: "",
        click: false, //是否显示弹窗内容
        option: false, //显示弹窗或关闭弹窗的操作动画
        checkedListNum: 1,
        // input默认是1
        num: 1,
        stock: 9999,
        // 使用data数据对象设置样式名
        minusStatus: 'disabled',
        plusStatus: 'normal',
        goodsInfo: {},
        specList: [],
        commentList: [],
        activityList: [],
        selectSpec: {},
        truePrice: 0
    },

    //通用的打印方法，用来查看当前事件传参
    consoleInfo(e) {
        console.log(e)
    },

    // 用户点击显示弹窗
    clickPup: function () {
        let _that = this;
        if (!_that.data.click) {
            _that.setData({
                click: true,
            })
        }
        if (_that.data.option) {
            _that.setData({
                option: false,
            })
            // 关闭显示弹窗动画的内容，不设置的话会出现：点击任何地方都会出现弹窗，就不是指定位置点击出现弹窗了
            setTimeout(() => {
                _that.setData({
                    click: false,
                })
            }, 500)
        } else {
            _that.setData({
                option: true
            })
        }
    },

    /* 点击减号 */
    bindMinus: function () {
        var num = this.data.num;
        // 如果大于1时，才可以减
        if (num > 1) {
            num--;
        }
        // 只有大于一件的时候，才能normal状态，否则disable状态
        var minusStatus = num <= 1 ? 'disabled' : 'normal';
        // 将数值与状态写回
        this.setData({
            num: num,
            minusStatus: minusStatus
        });
    },
    /* 点击加号 */
    bindPlus: function () {
        var num = this.data.num;
        var max = this.data.stock;
        //如果不超过库存，增1
        if (num < max) {
            num++;
        }
        // 只有小于库存的时候，才能normal状态，否则disable状态
        var plusStatus = num >= max ? 'disabled' : 'normal';
        // 只有大于一件的时候，才能normal状态，否则disable状态
        var minusStatus = num < 1 ? 'disabled' : 'normal';
        // 将数值与状态写回
        this.setData({
            num: num,
            minusStatus: minusStatus,
            plusStatus: plusStatus
        });
    },
    /* 输入框事件 */
    bindManual: function (e) {
        var num = parseInt(e.detail.value);
        var max = parseInt(this.data.stock);
        // 将数值与状态写回
        if (!(num === NaN || num < 1 || num > max)) {
            this.setData({
                num: num
            });
        } else if (num < 1) {
            this.setData({
                num: 1
            });
        } else if (num > max) {
            this.setData({
                num: max
            });
        }
    },

    // 切换分类
    scrollTo(e) {
        console.log(e.target.dataset.tab)
        this.setData({
            tab: e.target.dataset.tab
        })
    },

    login() {
        console.log("调用了登录接口！")
        let code
        wx.login({
            success(res) {
                if (res.code) {
                    code = res.code
                } else {
                    console.log('登录失败！' + res.errMsg)
                }
            }
        })
        wx.getUserProfile({
            desc: '为您带来带来更好使用体验！', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                wx.request({
                    url: 'https://mbp.jyccloud.cn/mbp/wxLogin',
                    method: 'post',
                    data: JSON.stringify({
                        name: res.userInfo.nickName,
                        avatarUrl: res.userInfo.avatarUrl,
                        code: code
                    }),
                    success: (res1) => {
                        const resData = res1.data[0]
                        wx.request({
                            url: 'https://mbp.jyccloud.cn/mbp/getCartList',
                            method: 'post',
                            data: JSON.stringify({
                                openId: resData.openId
                            }),
                            success: (res2) => {
                                console.log(res2.data)
                                try {
                                    wx.setStorageSync("cart", res2.data)
                                } catch (e) {
                                    console.warn(e)
                                } finally {
                                    this.triggerEvent("reloadPage", {});
                                }
                            }
                        }),
                            console.log(resData)
                        const userType = resData.userType
                        const PCNum = resData.PCId && resData.PCId !== "" ? resData.PCId.split(",").length : 0
                        const ACNum = resData.ACId && resData.ACId !== "" ? resData.ACId.split(",").length : 0
                        const PLNum = resData.PLId && resData.PLId !== "" ? resData.PLId.split(",").length : 0
                        const ALNum = resData.ALId && resData.ALId !== "" ? resData.ALId.split(",").length : 0
                        try {
                            wx.setStorageSync("userType", resData.userType)
                            wx.setStorageSync("PCId", resData.PCId)
                            wx.setStorageSync("PLId", resData.PLId)
                            wx.setStorageSync("ACId", resData.ACId)
                            wx.setStorageSync("ALId", resData.ALId)
                            wx.setStorageSync("collectNum", PCNum + ACNum)
                            wx.setStorageSync("likeNum", PLNum + ALNum)
                            wx.setStorageSync("points", resData.points)
                            wx.setStorageSync("balance", resData.balance)
                            wx.setStorageSync("name", resData.name)
                            wx.setStorageSync("openId", resData.openId)
                            wx.setStorageSync("avatarUrl", resData.avatarUrl)
                        } catch (e) {
                            console.warn(e)
                        } finally {
                            this.triggerEvent("reloadPage", {});
                        }
                    }
                })
            }
        })
    },

    //加入购物车
    clickAddCart() {
        if (wx.getStorageSync('openId') && wx.getStorageSync('openId') !== "" ? wx.getStorageSync('openId') : "") {
            const openId = wx.getStorageSync('openId')
            wx.request({
                url: 'https://mbp.jyccloud.cn/mbp/addCart',
                method: "POST",
                data: JSON.stringify({
                    count: this.data.num,
                    openId: openId,
                    productId: this.data.goodsInfo.productId,
                    specId: this.data.selectSpec.specId
                })
            })
        } else {
            this.login()
        }
    },

    //立即购买
    clickBuy() {
        if (wx.getStorageSync('openId') && wx.getStorageSync('openId') !== "" ? wx.getStorageSync('openId') : "") {
            const openId = wx.getStorageSync('openId')

            wx.setStorageSync('order', [{
                openId: openId,
                productId: this.data.goodsInfo.productId,
                specId: this.data.selectSpec.specId,
                count: this.data.num,
                title: this.data.goodsInfo.name,
                specName: this.data.selectSpec.specName,
                imageUrl: this.data.selectSpec.imageUrl !== "" ? this.data.selectSpec.imageUrl : this.data.goodsInfo.imageUrl,
                dPrice: (this.data.selectSpec.price - this.data.truePrice) * this.data.num,
                price: this.data.truePrice * this.data.num
            }])
            wx.navigateTo({
                url: "../settlementPage/index"
            })
        } else {
            this.login()
        }
    },


    changeSpec(e) {
        const id = parseInt(e.target.id)
        const select = this.data.specList.filter(item => item.specId === id)[0]
        const userType = wx.getStorageSync('userType') && wx.getStorageSync('userType') !== "" ? parseInt(wx.getStorageSync('userType')) : 0
        const price = userType === 1 ? select.tradePrice : select.price
        this.setData({
            selectSpec: select,
            truePrice: price
        })
    },

    toCart() {
        wx.switchTab({
            url: "../shoppingCart/index"
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var goodsId = options.goodsId
        wx.request({
            url: 'https://mbp.jyccloud.cn/mbp/getProductById',
            method: 'post',
            data: JSON.stringify({
                productId: goodsId
            }),
            success: (res) => {
                const activityMsg = res.data.activityList.map(r => {
                    return r.activityType === "满减" ? "满" + r.minPrice + "减" + r.activity : r.activityType === "买赠" ? "买" + r.minPrice + "赠" + r.activity : r.activityType === "折扣" ? r.minPrice !== 0 ? "满" + r.minPrice + "元" + r.activity + "折" : r.activity + "折" : ""
                })
                const userType = wx.getStorageSync('userType') && wx.getStorageSync('userType') !== "" ? parseInt(wx.getStorageSync('userType')) : 0
                this.setData({
                    goodsInfo: res.data["productInfo"][0],
                    specList: res.data["productSpec"],
                    commentList: res.data["productSpec"],
                    activityList: activityMsg,
                    truePrice: userType === 1 ? res.data["productSpec"][0].tradePrice : res.data["productSpec"][0].price,
                    selectSpec: res.data["productSpec"][0]
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})